package com.axinfu.util.config.util;

import com.axinfu.util.config.BtgSetPlugin;
import com.axinfu.util.encrypt.Encryption;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Objects;

/**
 * BtgSetUtils
 *
 * @author zjn
 * @since 2022/3/24
 */
public class BtgSetUtils {

    private static final String G = "-";
    private static final int INT_10 = 10;

    /**
     * 验证当前登录用户是否过期
     *
     * @param key key
     * @return boolean
     */
    public static boolean valid(String key) {
        if ("".equals(key) || key == null || !key.contains(G)) {
            return false;
        }

        String seed = key.substring(0, key.indexOf("-"));
        if (seed.length() < INT_10) {
            return false;
        }
        long times;
        try {
            times = Long.parseLong(seed);
        } catch (Exception e) {
            return false;
        }
        String re = getKey(times);

        if (!key.equals(re)) {
            return false;
        }

        long curr = System.currentTimeMillis();

        if (curr < times) {
            return false;
        }

        long sec = curr - times;

        return (long) BtgSetPlugin.getBtgSetPlugin().getSessionTimeOut() * 60 * 1000 >= sec;
    }

    public static String getKey(long times) {
        String key = Long.toString(times);
        int i = Integer.parseInt(key.substring(7));
        i = i << Integer.parseInt(key.substring(4, 5));
        try {
            key = Objects.requireNonNull(Encryption.encryptMd5ToHex(Integer.toBinaryString(i))).toUpperCase();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return times + "-" + key;
    }

    /**
     * closeDb
     *
     * @param conn       conn
     * @param statement1 statement1
     * @param statement2 statement2
     * @param rs         rs
     */
    public static void closeDb(Connection conn, Statement statement1, Statement statement2, ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
            }
            if (statement1 != null) {
                statement1.close();
            }
            if (statement2 != null) {
                statement2.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
